import React, { useState, useEffect } from "react";
import {
  Avatar,
  Radio,
  Modal,
  Button,
  Input,
  Upload,
  Icon,
  notification,
  message
} from "antd";
import config from "../../../../config";
import { connect } from "react-redux";
import bg from "assets/images/bg4.jpg";
import {
  getUserDetail,
  getAvatarList,
  updateUserDetail,
  getBackground
} from "../../../../utils/api/userApi";
import { setUserData as updateUserData } from "../../../../stores/homeStore/action";
import { uploadAvatar } from "../../../../utils/api/userApi";

const User = ({ updateUserData }) => {
  const [isShowModal, setShowModal] = useState(false);
  const [userData, setUserData] = useState({});
  const [avatarList, setAvatarList] = useState([]);
  const [tempAvatar, setTempAvatar] = useState("");
  const [tempName, setTempName] = useState();
  const [isShowEdit, setShowEdit] = useState(false);
  const [bg_url, setBgUrl] = useState();
  const [imgUpload, setImageUpload] = useState({
    isLoading: false,
    imageUrl: ""
  });

  const handleModalOk = () => {
    setShowModal(false);
    setUserData({
      ...userData,
      avatar: tempAvatar
    });
  };

  const handleModalCancel = () => {
    setShowModal(false);
  };

  const handleChangeSex = ev => {
    let value = ev.target.value;
    setUserData({
      ...userData,
      sex: value
    });
  };

  const handleShowEdit = () => {
    setShowEdit(true);
  };

  const handleEditInput = ev => {
    const value = ev.target.value;
    setTempName(value);
  };
  const handleEditCancel = () => {
    setTempName();
    setShowEdit(false);
  };
  const handleEditOk = () => {
    setUserData({
      ...userData,
      name: tempName
    });
    setShowEdit(false);
    setTempName();
  };

  const handleSubmitClick = () => {
    Modal.confirm({
      title: "修改用户资料",
      content: "您确定要修改个人资料吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        updateUserDetail(userData)
          .then(data => {
            if (data.err === 0) {
              notification["success"]({
                message: data.msg
              });
              updateUserData(userData);
            } else {
              notification["error"]({
                message: data.msg
              });
            }
          })
          .catch(err => {
            notification["error"]({
              message: err
            });
          });
      }
    });
  };

  useEffect(() => {
    getUserDetail().then(res => {
      if (res.err === 0) {
        setUserData(res.data);
      }
    });
    getAvatarList().then(res => {
      if (res.err === 0) {
        setAvatarList(res.data);
      }
    });
    getBackground()
      .then(data => {
        setBgUrl(data);
      })
      .catch(err => {
        setBgUrl(bg);
      });
  }, []);

  function beforeUpload(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("只能上传JPG/PNG的文件!");
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error("图片最大伟5MB!");
    }
    return isJpgOrPng && isLt2M;
  }

  const handleUploadAvatar = (info) => {
    const {file} = info;
    const formData = new FormData();
    formData.append("image", file);
    setImageUpload({
      ...imgUpload,
      isLoading: true
    })
    uploadAvatar(formData).then(res => {
      if(res.err === 0) {
        message.success("头像上传成功");
        let newList = [...avatarList, res.img];
          setAvatarList(newList);
        setImageUpload({
          ...imgUpload,
          isLoading: false
        })
      }
    });
  }

  const { imageUrl, isLoading } = imgUpload;

  return (
    <div className="user">
      <div className="user-container">
        <div
          className="user-background"
          style={{ backgroundImage: `url(${bg_url})` }}
        ></div>
        <Avatar
          className="user-avatar"
          size={130}
          icon="user"
          src={config.api + userData.avatar}
        />
        <Modal
          title="选择头像"
          className="user-avatar-modal"
          visible={isShowModal}
          width={805}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
        >
          {avatarList.map(avatar => (
            <span
              key={avatar}
              className={
                avatar === tempAvatar ? "avatar-wrap active" : "avatar-wrap"
              }
              onClick={() => {
                setTempAvatar(avatar);
              }}
            >
              <Avatar shape="square" size={64} src={config.api + avatar} />
            </span>
          ))}
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            accept="image/*"
            beforeUpload={beforeUpload}
            customRequest={handleUploadAvatar}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
            ) : (
              <div>
                <Icon type={isLoading ? "loading" : "plus"} />
                <div className="ant-upload-text">上传</div>
              </div>
            )}
          </Upload>
        </Modal>
        <ul className="user-data">
          <li>
            头像
            <a
              className="data_content"
              onClick={() => {
                setShowModal(true);
              }}
            >
              更换头像
            </a>
          </li>
          <li className="user-name">
            昵称
            {isShowEdit ? (
              <>
                <Input className="user-name-input" onChange={handleEditInput} />
                <Icon
                  type="close-circle"
                  className="edit-btn-icon"
                  onClick={handleEditCancel}
                />
                <Icon
                  type="check-circle"
                  className="edit-btn-icon"
                  onClick={handleEditOk}
                />
              </>
            ) : (
              <span className="data_content">
                {userData.name || userData.us}
                <Icon
                  type="edit"
                  onClick={handleShowEdit}
                  className="user-edit-name"
                />
              </span>
            )}
          </li>
          <li>
            账号<span className="data_content">{userData.us}</span>
          </li>
          <li>
            密码<span className="data_content">******</span>
          </li>
          <li>
            性别
            <Radio.Group
              className="data_content"
              onChange={handleChangeSex}
              value={userData.sex}
            >
              <Radio value={0}>男</Radio>
              <Radio value={1}>女</Radio>
            </Radio.Group>
          </li>
          <li>
            邮箱<span className="data_content">{userData.email}</span>
          </li>
          <li className="data_btn">
            <Button onClick={handleSubmitClick}>确认修改</Button>
          </li>
        </ul>
      </div>
    </div>
  );
};

export default connect(store => ({}), {
  updateUserData
})(User);
